package cn.knightzz.service.impl;

import cn.knightzz.entity.SysMessage;
import cn.knightzz.mapper.SysMessageMapper;
import cn.knightzz.service.SysMessageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.cookie.SM;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author knightzz
 * @since 2021-05-07
 */
@Slf4j
@Service
public class SysMessageServiceImpl extends ServiceImpl<SysMessageMapper, SysMessage> implements SysMessageService {

    @Resource
    SysMessageMapper messageMapper;


    /**
     * 添加通知信息
     *
     * @param message
     * @return
     */
    @Override
    public Boolean addMessage(SysMessage message) {
        int row = 0;
        try {
            row = messageMapper.insert(message);
        } catch (Exception e) {
            log.error("addMessage error !!!!");
            log.error(e.getMessage());
            return false;
        }
        return row != 0;
    }

    /**
     * 获取当前用户发送的所有消息
     * @param pageNum
     * @param pageSize
     * @param query
     * @param userId
     * @return
     */
    @Override
    public IPage<SysMessage> getAllMessageByAuthorId(Long pageNum, Long pageSize, String query, Long userId) {

        Page<SysMessage> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);

        QueryWrapper<SysMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("author_id", userId);
        queryWrapper.orderByDesc("send_time");
        queryWrapper.like("title", query);

        try {
            return messageMapper.selectPage(page, queryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 更新消息内容
     *
     * @param message 最新的通知信息
     * @return 是否删除成功
     */
    @Override
    public Boolean updateMessage(SysMessage message) {
        int row = 0;
        try {
            row = messageMapper.updateById(message);
        } catch (Exception e) {
            log.error("updateMessage error ...");
            log.error(e.getMessage());
            return false;
        }
        return row != 0;
    }

    /**
     * 删除通知信息
     *
     * @param messageId
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteMessage(Long messageId) {
        int row = 0;
        try {
            row = messageMapper.deleteById(messageId);
        } catch (Exception e) {
            log.error("deleteMessage error ...");
            log.error(e.getMessage());
            return false;
        }
        return row != 0;
    }
}
